package com.wind.utils.thread;

import java.util.concurrent.*;

/**
 * <p>
 *      线程池
 * </p>
 * @author wind
 * @date    2024/12/11 11:27
 * @version v1.0
 */
public class ThreadPoolUtil {


    private ThreadPoolUtil(){
        
    }

    /**
     * 创建具有固定线程数的线程池
     *
     * @param nThreads 线程池大小
     * @return 线程池实例
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return Executors.newFixedThreadPool(nThreads);
    }

    /**
     * 创建单线程的缓存线程池
     *
     * @return 线程池实例
     */
    public static ExecutorService newSingleThreadExecutor() {
        return Executors.newSingleThreadExecutor();
    }

    /**
     * 创建可缓存的线程池
     *
     * @return 线程池实例
     */
    public static ExecutorService newCachedThreadPool() {
        return Executors.newCachedThreadPool();
    }


    /**
     * 自定义线程池
     * @param coreSize
     * @param maximumSize
     * @param keepAliveTime
     * @param unit
     * @param workQueue
     * @return
     */
    public static ExecutorService customThreadPool(int coreSize, int maximumSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        return new ThreadPoolExecutor(
                coreSize,
                maximumSize,
                keepAliveTime,
                unit,
                workQueue,
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r);
                    }
                },
                (r, executor) -> {
                    // 处理任务拒绝情况
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
        );
    }

    /**
     * 提交任务到线程池
     *
     * @param executor 线程池
     * @param task     任务
     */
    public static void execute(ExecutorService executor, Runnable task) {
        executor.execute(task);
    }



    /**
     * 关闭线程池（不立即终止，等待任务执行完成）
     *
     * @param executor 线程池
     * @param timeout  超时时间
     * @param unit     时间单位
     * @throws InterruptedException 如果等待过程被中断
     */
    public static void shutdown(ExecutorService executor, long timeout, TimeUnit unit) throws InterruptedException {
        executor.shutdown();
        if (!executor.awaitTermination(timeout, unit)) {
            System.out.println("线程池中的任务未能在指定时间内完成执行，将强制关闭线程池。");
            executor.shutdownNow(); // 尝试立即停止所有正在执行的任务
            if (!executor.awaitTermination(timeout, unit)) {
                System.out.println("线程池中的任务无法响应中断，可能没有正确处理任务执行。");
            }
        }
    }

    /**
     * 关闭线程池（尝试立即终止）
     *
     * @param executor 线程池
     */
    public static void shutdownNow(ExecutorService executor) {
        executor.shutdownNow();
    }

    /**
     * 优雅地关闭线程池
     *
     * @param executor 线程池
     */
    public static void shutdown(ExecutorService executor) {
        executor.shutdown(); // 首先拒绝新任务
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow(); // 然后尝试立即停止
            }
        } catch (InterruptedException ex) {
            executor.shutdownNow();
            Thread.currentThread().interrupt(); // 保留中断状态
        }
    }
}